<template>
  <view class="stats-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">数据统计</text>
      </view>
      <view class="navbar-action" @tap="exportData">
        <text class="action-text">导出</text>
      </view>
    </view>

    <!-- 总览卡片 -->
    <view class="overview-card">
      <view class="overview-header">
        <text class="overview-title">使用概览</text>
        <text class="overview-period">{{ currentPeriod }}</text>
      </view>
      
      <view class="overview-stats">
        <view class="stat-item">
          <text class="stat-number">{{ totalDays }}</text>
          <text class="stat-label">使用天数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ totalRecords }}</text>
          <text class="stat-label">情绪记录</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ totalTests }}</text>
          <text class="stat-label">心理测评</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ totalCourses }}</text>
          <text class="stat-label">课程学习</text>
        </view>
      </view>
    </view>

    <!-- 时间选择 -->
    <view class="period-selector">
      <view 
        class="period-tab" 
        :class="{ active: activePeriod === period.key }"
        v-for="period in periodOptions" 
        :key="period.key"
        @tap="changePeriod(period.key)"
      >
        <text class="period-text">{{ period.label }}</text>
      </view>
    </view>

    <!-- 情绪趋势图 -->
    <view class="chart-card">
      <view class="chart-header">
        <text class="chart-title">情绪趋势</text>
        <text class="chart-subtitle">平均情绪强度变化</text>
      </view>
      
      <view class="chart-container">
        <canvas 
          canvas-id="moodChart" 
          class="mood-chart"
          @touchstart="onChartTouch"
        ></canvas>
      </view>
      
      <view class="chart-legend">
        <view class="legend-item">
          <view class="legend-color mood-positive"></view>
          <text class="legend-text">积极情绪</text>
        </view>
        <view class="legend-item">
          <view class="legend-color mood-neutral"></view>
          <text class="legend-text">平静情绪</text>
        </view>
        <view class="legend-item">
          <view class="legend-color mood-negative"></view>
          <text class="legend-text">消极情绪</text>
        </view>
      </view>
    </view>

    <!-- 情绪分布 -->
    <view class="distribution-card">
      <view class="card-header">
        <text class="card-title">情绪分布</text>
        <text class="card-subtitle">各类情绪占比</text>
      </view>
      
      <view class="mood-distribution">
        <view class="mood-item" v-for="mood in moodDistribution" :key="mood.name">
          <view class="mood-info">
            <text class="mood-emoji">{{ mood.emoji }}</text>
            <text class="mood-name">{{ mood.name }}</text>
          </view>
          <view class="mood-progress">
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: mood.percentage + '%', backgroundColor: mood.color }"></view>
            </view>
            <text class="progress-text">{{ mood.percentage }}%</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 测评历史 -->
    <view class="test-history-card">
      <view class="card-header">
        <text class="card-title">测评历史</text>
        <text class="card-subtitle">心理健康评估记录</text>
      </view>
      
      <view class="test-list">
        <view class="test-item" v-for="test in recentTests" :key="test.id">
          <view class="test-info">
            <text class="test-name">{{ test.name }}</text>
            <text class="test-date">{{ formatDate(test.date) }}</text>
          </view>
          <view class="test-result">
            <text class="test-score">{{ test.score }}分</text>
            <text class="test-level" :class="'level-' + test.level.toLowerCase()">{{ test.level }}</text>
          </view>
        </view>
      </view>
      
      <view class="view-all" @tap="viewAllTests">
        <text class="view-all-text">查看全部测评记录</text>
        <text class="view-all-icon">→</text>
      </view>
    </view>

    <!-- 学习统计 -->
    <view class="learning-card">
      <view class="card-header">
        <text class="card-title">学习统计</text>
        <text class="card-subtitle">课程学习进度</text>
      </view>
      
      <view class="learning-stats">
        <view class="learning-item">
          <view class="learning-icon">🧘</view>
          <view class="learning-info">
            <text class="learning-name">冥想练习</text>
            <text class="learning-time">{{ formatTime(meditationTime) }}</text>
          </view>
          <view class="learning-count">
            <text class="count-number">{{ meditationCount }}</text>
            <text class="count-label">次</text>
          </view>
        </view>
        
        <view class="learning-item">
          <view class="learning-icon">💆</view>
          <view class="learning-info">
            <text class="learning-name">情绪疏导</text>
            <text class="learning-time">{{ formatTime(guidanceTime) }}</text>
          </view>
          <view class="learning-count">
            <text class="count-number">{{ guidanceCount }}</text>
            <text class="count-label">次</text>
          </view>
        </view>
        
        <view class="learning-item">
          <view class="learning-icon">🫁</view>
          <view class="learning-info">
            <text class="learning-name">呼吸练习</text>
            <text class="learning-time">{{ formatTime(breathingTime) }}</text>
          </view>
          <view class="learning-count">
            <text class="count-number">{{ breathingCount }}</text>
            <text class="count-label">次</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 成就进度 -->
    <view class="achievement-card">
      <view class="card-header">
        <text class="card-title">成就进度</text>
        <text class="card-subtitle">解锁更多徽章</text>
      </view>
      
      <view class="achievement-list">
        <view class="achievement-item" v-for="achievement in achievements" :key="achievement.id">
          <view class="achievement-icon" :class="{ unlocked: achievement.unlocked }">
            <text class="icon-text">{{ achievement.icon }}</text>
          </view>
          <view class="achievement-info">
            <text class="achievement-name">{{ achievement.name }}</text>
            <text class="achievement-desc">{{ achievement.description }}</text>
            <view class="achievement-progress">
              <view class="progress-bar">
                <view class="progress-fill" :style="{ width: achievement.progress + '%' }"></view>
              </view>
              <text class="progress-text">{{ achievement.current }}/{{ achievement.target }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 隐藏的Canvas元素用于PDF和图片生成 -->
    <canvas 
      id="pdf-canvas" 
      style="position: fixed; top: -9999px; left: -9999px; width: 595px; height: 842px;"
      canvas-id="pdf-canvas"
    ></canvas>
    <canvas 
      id="share-canvas" 
      style="position: fixed; top: -9999px; left: -9999px; width: 750px; height: 1334px;"
      canvas-id="share-canvas"
    ></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activePeriod: 'month',
      currentPeriod: '本月',
      totalDays: 0,
      totalRecords: 0,
      totalTests: 0,
      totalCourses: 0,
      moodData: [],
      testData: [],
      courseData: [],
      
      periodOptions: [
        { key: 'week', label: '本周' },
        { key: 'month', label: '本月' },
        { key: 'quarter', label: '本季度' },
        { key: 'year', label: '本年' }
      ],
      
      moodDistribution: [],
      testResults: [],
      courseProgress: [],
      
      chartContext: null
    }
  },
  
  onLoad() {
    this.loadStatisticsData()
    this.initChart()
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    loadStatisticsData() {
      try {
        // 加载情绪记录数据
        const moodRecords = uni.getStorageSync('mood_records') || []
        const testHistory = uni.getStorageSync('test_history') || []
        const courseHistory = uni.getStorageSync('course_history') || []
        
        this.calculateOverviewStats(moodRecords, testHistory, courseHistory)
        this.calculateMoodDistribution(moodRecords)
        this.calculateTestResults(testHistory)
        this.calculateCourseProgress(courseHistory)
        this.prepareMoodChartData(moodRecords)
        
      } catch (e) {
        console.error('加载统计数据失败:', e)
        this.showDefaultData()
      }
    },
    
    calculateOverviewStats(moodRecords, testHistory, courseHistory) {
      const now = new Date()
      const periodStart = this.getPeriodStart(now, this.activePeriod)
      
      // 筛选时间范围内的数据
      const filteredMoods = moodRecords.filter(record => 
        new Date(record.createTime || record.date) >= periodStart
      )
      const filteredTests = testHistory.filter(test => 
        new Date(test.date) >= periodStart
      )
      const filteredCourses = courseHistory.filter(course => 
        new Date(course.date) >= periodStart
      )
      
      // 计算使用天数
      const uniqueDays = new Set()
      filteredMoods.forEach(record => {
        uniqueDays.add(new Date(record.createTime || record.date).toDateString())
      })
      filteredTests.forEach(test => {
        uniqueDays.add(new Date(test.date).toDateString())
      })
      filteredCourses.forEach(course => {
        uniqueDays.add(new Date(course.date).toDateString())
      })
      
      this.totalDays = uniqueDays.size
      this.totalRecords = filteredMoods.length
      this.totalTests = filteredTests.length
      this.totalCourses = filteredCourses.length
    },
    
    calculateMoodDistribution(moodRecords) {
      const moodCount = {}
      const moodEmojis = {
        '开心': '😊',
        '平静': '😌',
        '焦虑': '😰',
        '难过': '😢',
        '愤怒': '😠',
        '兴奋': '🤩',
        '疲惫': '😴',
        '困惑': '😕'
      }
      
      moodRecords.forEach(record => {
        const mood = record.mood
        moodCount[mood] = (moodCount[mood] || 0) + 1
      })
      
      const total = moodRecords.length || 1
      this.moodDistribution = Object.entries(moodCount).map(([mood, count]) => ({
        name: mood,
        emoji: moodEmojis[mood] || '😐',
        count: count,
        percentage: Math.round((count / total) * 100)
      })).sort((a, b) => b.count - a.count)
    },
    
    calculateTestResults(testHistory) {
      const testTypes = {}
      
      testHistory.forEach(test => {
        if (!testTypes[test.type]) {
          testTypes[test.type] = {
            type: test.type,
            name: this.getTestName(test.type),
            scores: [],
            latestScore: 0,
            trend: 'stable'
          }
        }
        testTypes[test.type].scores.push({
          score: test.score,
          date: test.date
        })
      })
      
      // 计算趋势和最新分数
      Object.values(testTypes).forEach(testType => {
        testType.scores.sort((a, b) => new Date(a.date) - new Date(b.date))
        testType.latestScore = testType.scores[testType.scores.length - 1]?.score || 0
        
        if (testType.scores.length >= 2) {
          const recent = testType.scores.slice(-3).map(s => s.score)
          const avg = recent.reduce((sum, score) => sum + score, 0) / recent.length
          const firstScore = testType.scores[0].score
          
          if (avg > firstScore + 5) {
            testType.trend = 'up'
          } else if (avg < firstScore - 5) {
            testType.trend = 'down'
          }
        }
      })
      
      this.testResults = Object.values(testTypes)
    },
    
    calculateCourseProgress(courseHistory) {
      const courseTypes = {}
      
      courseHistory.forEach(course => {
        if (!courseTypes[course.type]) {
          courseTypes[course.type] = {
            type: course.type,
            name: course.name || this.getCourseName(course.type),
            totalTime: 0,
            completedSessions: 0,
            lastStudied: null
          }
        }
        
        courseTypes[course.type].totalTime += course.duration || 0
        courseTypes[course.type].completedSessions += 1
        
        if (!courseTypes[course.type].lastStudied || 
            new Date(course.date) > new Date(courseTypes[course.type].lastStudied)) {
          courseTypes[course.type].lastStudied = course.date
        }
      })
      
      this.courseProgress = Object.values(courseTypes)
    },
    
    prepareMoodChartData(moodRecords) {
      const now = new Date()
      const periodStart = this.getPeriodStart(now, this.activePeriod)
      const days = this.getDaysInPeriod(this.activePeriod)
      
      const dailyMoods = {}
      
      // 初始化每日数据
      for (let i = 0; i < days; i++) {
        const date = new Date(periodStart)
        date.setDate(date.getDate() + i)
        const dateStr = date.toDateString()
        dailyMoods[dateStr] = {
          date: dateStr,
          moods: [],
          averageIntensity: 0
        }
      }
      
      // 填充实际数据
      moodRecords.forEach(record => {
        const recordDate = new Date(record.createTime || record.date)
        if (recordDate >= periodStart) {
          const dateStr = recordDate.toDateString()
          if (dailyMoods[dateStr]) {
            dailyMoods[dateStr].moods.push({
              mood: record.mood,
              intensity: record.intensity || 5
            })
          }
        }
      })
      
      // 计算每日平均强度
      Object.values(dailyMoods).forEach(day => {
        if (day.moods.length > 0) {
          const totalIntensity = day.moods.reduce((sum, mood) => sum + mood.intensity, 0)
          day.averageIntensity = totalIntensity / day.moods.length
        }
      })
      
      this.moodData = Object.values(dailyMoods)
      this.drawMoodChart()
    },
    
    initChart() {
      this.chartContext = uni.createCanvasContext('moodChart', this)
    },
    
    drawMoodChart() {
      if (!this.chartContext || this.moodData.length === 0) return
      
      const ctx = this.chartContext
      const canvasWidth = 300
      const canvasHeight = 200
      const padding = 40
      const chartWidth = canvasWidth - padding * 2
      const chartHeight = canvasHeight - padding * 2
      
      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制背景
      ctx.setFillStyle('#f8f9fa')
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制网格线
      ctx.setStrokeStyle('#e9ecef')
      ctx.setLineWidth(1)
      
      // 水平网格线
      for (let i = 0; i <= 5; i++) {
        const y = padding + (chartHeight / 5) * i
        ctx.beginPath()
        ctx.moveTo(padding, y)
        ctx.lineTo(canvasWidth - padding, y)
        ctx.stroke()
      }
      
      // 垂直网格线
      const dataPoints = this.moodData.length
      for (let i = 0; i <= dataPoints - 1; i++) {
        const x = padding + (chartWidth / (dataPoints - 1)) * i
        ctx.beginPath()
        ctx.moveTo(x, padding)
        ctx.lineTo(x, canvasHeight - padding)
        ctx.stroke()
      }
      
      // 绘制数据线
      if (dataPoints > 1) {
        ctx.setStrokeStyle('#667eea')
        ctx.setLineWidth(3)
        ctx.beginPath()
        
        this.moodData.forEach((point, index) => {
          const x = padding + (chartWidth / (dataPoints - 1)) * index
          const y = canvasHeight - padding - (point.averageIntensity / 10) * chartHeight
          
          if (index === 0) {
            ctx.moveTo(x, y)
          } else {
            ctx.lineTo(x, y)
          }
        })
        
        ctx.stroke()
        
        // 绘制数据点
        ctx.setFillStyle('#667eea')
        this.moodData.forEach((point, index) => {
          const x = padding + (chartWidth / (dataPoints - 1)) * index
          const y = canvasHeight - padding - (point.averageIntensity / 10) * chartHeight
          
          ctx.beginPath()
          ctx.arc(x, y, 4, 0, 2 * Math.PI)
          ctx.fill()
        })
      }
      
      // 绘制坐标轴标签
      ctx.setFillStyle('#666')
      ctx.setFontSize(12)
      
      // Y轴标签
      for (let i = 0; i <= 5; i++) {
        const y = canvasHeight - padding - (chartHeight / 5) * i
        const value = (i * 2).toString()
        ctx.fillText(value, 10, y + 4)
      }
      
      ctx.draw()
    },
    
    getPeriodStart(now, period) {
      const start = new Date(now)
      
      switch (period) {
        case 'week':
          start.setDate(start.getDate() - start.getDay())
          break
        case 'month':
          start.setDate(1)
          break
        case 'quarter':
          const quarter = Math.floor(start.getMonth() / 3)
          start.setMonth(quarter * 3, 1)
          break
        case 'year':
          start.setMonth(0, 1)
          break
      }
      
      start.setHours(0, 0, 0, 0)
      return start
    },
    
    getDaysInPeriod(period) {
      switch (period) {
        case 'week': return 7
        case 'month': return 30
        case 'quarter': return 90
        case 'year': return 365
        default: return 30
      }
    },
    
    changePeriod(period) {
      this.activePeriod = period
      this.currentPeriod = this.periodOptions.find(p => p.key === period)?.label || '本月'
      this.loadStatisticsData()
    },
    
    getTestName(type) {
      const testNames = {
        'anxiety': '焦虑测评',
        'depression': '抑郁测评',
        'stress': '压力测评',
        'sleep': '睡眠质量',
        'self_esteem': '自尊水平'
      }
      return testNames[type] || type
    },
    
    getCourseName(type) {
      const courseNames = {
        'meditation': '冥想课程',
        'breathing': '呼吸练习',
        'relaxation': '放松训练',
        'mindfulness': '正念练习'
      }
      return courseNames[type] || type
    },
    
    showDefaultData() {
      this.totalDays = 0
      this.totalRecords = 0
      this.totalTests = 0
      this.totalCourses = 0
      this.moodDistribution = []
      this.testResults = []
      this.courseProgress = []
      this.moodData = []
    },
    
    exportData() {
      uni.showActionSheet({
        itemList: ['导出PDF报告', '导出Excel数据', '分享图片'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.exportPDF()
              break
            case 1:
              this.exportExcel()
              break
            case 2:
              this.shareImage()
              break
          }
        }
      })
    },
    
    async exportPDF() {
      uni.showLoading({ title: '生成PDF中...' })
      
      try {
        // 动态导入PDF导出工具
        const PDFExport = (await import('../../utils/pdfExport.js')).default
        const pdfExporter = new PDFExport()
        
        // 准备数据
        const reportData = {
          title: '情绪大师 - 个人统计报告',
          period: this.currentPeriod,
          generateTime: new Date().toLocaleString(),
          overview: {
            totalDays: this.totalDays,
            totalRecords: this.totalRecords,
            totalTests: this.totalTests,
            totalCourses: this.totalCourses
          },
          moodDistribution: this.moodDistribution,
          testResults: this.testResults,
          courseProgress: this.courseProgress
        }
        
        // 生成PDF
        const pdfPath = await pdfExporter.generateMoodReport(reportData)
        
        uni.hideLoading()
        
        // 分享PDF
        await pdfExporter.sharePDF(pdfPath)
        
      } catch (error) {
        uni.hideLoading()
        console.error('导出PDF失败:', error)
        uni.showToast({
          title: '导出失败',
          icon: 'error'
        })
      }
    },
    
    async exportExcel() {
      uni.showLoading({ title: '生成Excel中...' })
      
      try {
        // 动态导入Excel导出工具
        const ExcelExport = (await import('../../utils/excelExport.js')).default
        const excelExporter = new ExcelExport()
        
        // 获取情绪记录数据
        const moodRecords = uni.getStorageSync('mood_records') || []
        const testHistory = uni.getStorageSync('test_history') || []
        
        // 生成Excel文件
        let excelPath
        if (moodRecords.length > 0) {
          excelPath = await excelExporter.generateMoodRecordsExcel(moodRecords)
        } else if (testHistory.length > 0) {
          excelPath = await excelExporter.generateTestResultsExcel(testHistory)
        } else {
          throw new Error('没有可导出的数据')
        }
        
        uni.hideLoading()
        
        // 分享Excel
        await excelExporter.shareExcel(excelPath)
        
      } catch (error) {
        uni.hideLoading()
        console.error('导出Excel失败:', error)
        uni.showToast({
          title: error.message || '导出失败',
          icon: 'error'
        })
      }
    },
    
    async shareImage() {
      uni.showLoading({ title: '生成分享图中...' })
      
      try {
        // 动态导入图片分享工具
        const ImageShare = (await import('../../utils/imageShare.js')).default
        const imageSharer = new ImageShare()
        
        // 准备数据
        const shareData = {
          title: '我的情绪统计',
          period: this.currentPeriod,
          stats: {
            days: this.totalDays,
            records: this.totalRecords,
            tests: this.totalTests
          },
          topMood: this.moodDistribution[0] || { name: '平静', emoji: '😌' },
          moodTrend: this.moodData
        }
        
        // 生成分享图
        const imagePath = await imageSharer.generateMoodStatsImage(shareData)
        
        uni.hideLoading()
        
        // 分享图片
        await imageSharer.shareImage(imagePath, '我的情绪统计报告')
        
      } catch (error) {
        uni.hideLoading()
        console.error('分享图片失败:', error)
        uni.showToast({
          title: '分享失败',
          icon: 'error'
        })
      }
    },
    
    generatePDFContent(data) {
      return `
# ${data.title}

## 报告概览
- 统计周期：${data.period}
- 生成时间：${data.generateTime}

## 使用统计
- 使用天数：${data.overview.totalDays} 天
- 情绪记录：${data.overview.totalRecords} 条
- 心理测评：${data.overview.totalTests} 次
- 课程学习：${data.overview.totalCourses} 次

## 情绪分布
${data.moodDistribution.map(mood => 
  `- ${mood.emoji} ${mood.name}：${mood.count} 次 (${mood.percentage}%)`
).join('\n')}

## 测评结果
${data.testResults.map(test => 
  `- ${test.name}：最新得分 ${test.latestScore} 分`
).join('\n')}

## 课程进度
${data.courseProgress.map(course => 
  `- ${course.name}：学习 ${course.completedSessions} 次，总时长 ${Math.round(course.totalTime/60)} 分钟`
).join('\n')}
      `
    },
    
    generateExcelData() {
      return {
        overview: [
          ['统计项目', '数值'],
          ['使用天数', this.totalDays],
          ['情绪记录', this.totalRecords],
          ['心理测评', this.totalTests],
          ['课程学习', this.totalCourses]
        ],
        moodDistribution: [
          ['情绪类型', '次数', '占比'],
          ...this.moodDistribution.map(mood => [mood.name, mood.count, mood.percentage + '%'])
        ],
        testResults: [
          ['测评类型', '最新得分', '趋势'],
          ...this.testResults.map(test => [test.name, test.latestScore, test.trend])
        ]
      }
    },
    
    convertToCSV(data) {
      let csv = ''
      
      // 概览数据
      csv += '使用概览\n'
      data.overview.forEach(row => {
        csv += row.join(',') + '\n'
      })
      csv += '\n'
      
      // 情绪分布
      csv += '情绪分布\n'
      data.moodDistribution.forEach(row => {
        csv += row.join(',') + '\n'
      })
      csv += '\n'
      
      // 测评结果
      csv += '测评结果\n'
      data.testResults.forEach(row => {
        csv += row.join(',') + '\n'
      })
      
      return csv
    },
    
    onChartTouch(e) {
      // 图表交互处理
      console.log('图表触摸事件:', e)
    }
  }
}
</script>

<style scoped>
.stats-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding-bottom: 30rpx;
}

/* 导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
}

.navbar-action {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-text {
  font-size: 28rpx;
}

/* 总览卡片 */
.overview-card {
  background: white;
  margin: 30rpx;
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.overview-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
}

.overview-period {
  font-size: 26rpx;
  color: var(--text-tertiary);
}

.overview-stats {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  color: var(--primary-color);
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

/* 时间选择 */
.period-selector {
  display: flex;
  margin: 0 30rpx 30rpx;
  background: white;
  border-radius: 25rpx;
  padding: 8rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.period-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  border-radius: 20rpx;
}

.period-tab.active {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
}

.period-text {
  font-size: 26rpx;
  color: var(--text-secondary);
}

.period-tab.active .period-text {
  color: white;
  font-weight: 600;
}

/* 图表卡片 */
.chart-card {
  background: white;
  margin: 0 30rpx 30rpx;
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.chart-header {
  margin-bottom: 30rpx;
}

.chart-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
}

.chart-subtitle {
  font-size: 26rpx;
  color: var(--text-tertiary);
}

.chart-container {
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
}

.mood-chart {
  width: 600rpx;
  height: 400rpx;
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 40rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.legend-color {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
}

.mood-positive {
  background: #4CAF50;
}

.mood-neutral {
  background: #2196F3;
}

.mood-negative {
  background: #FF9800;
}

.legend-text {
  font-size: 24rpx;
  color: var(--text-secondary);
}

/* 通用卡片样式 */
.distribution-card,
.test-history-card,
.learning-card,
.achievement-card {
  background: white;
  margin: 0 30rpx 30rpx;
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  margin-bottom: 30rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
}

.card-subtitle {
  font-size: 26rpx;
  color: var(--text-tertiary);
}

/* 情绪分布 */
.mood-distribution {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.mood-item {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.mood-info {
  display: flex;
  align-items: center;
  gap: 15rpx;
  min-width: 160rpx;
}

.mood-emoji {
  font-size: 36rpx;
}

.mood-name {
  font-size: 28rpx;
  color: var(--text-primary);
}

.mood-progress {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.progress-bar {
  flex: 1;
  height: 12rpx;
  background: var(--border-color);
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 24rpx;
  color: var(--text-secondary);
  min-width: 60rpx;
  text-align: right;
}

/* 测评历史 */
.test-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.test-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: var(--background-light);
  border-radius: 12rpx;
}

.test-info {
  flex: 1;
}

.test-name {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 8rpx;
}

.test-date {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.test-result {
  text-align: right;
}

.test-score {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--primary-color);
  display: block;
  margin-bottom: 5rpx;
}

.test-level {
  font-size: 24rpx;
  padding: 6rpx 12rpx;
  border-radius: 8rpx;
}

.level-low {
  background: #e8f5e8;
  color: #4caf50;
}

.level-normal {
  background: #e3f2fd;
  color: #2196f3;
}

.level-medium {
  background: #fff3e0;
  color: #ff9800;
}

.level-high {
  background: #ffebee;
  color: #f44336;
}

.view-all {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10rpx;
  padding: 20rpx;
  background: var(--accent-color);
  border-radius: 12rpx;
}

.view-all-text {
  font-size: 28rpx;
  color: var(--primary-color);
  font-weight: 600;
}

.view-all-icon {
  font-size: 24rpx;
  color: var(--primary-color);
}

/* 学习统计 */
.learning-stats {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.learning-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 25rpx;
  background: var(--background-light);
  border-radius: 16rpx;
}

.learning-icon {
  font-size: 48rpx;
  width: 80rpx;
  text-align: center;
}

.learning-info {
  flex: 1;
}

.learning-name {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 8rpx;
}

.learning-time {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.learning-count {
  text-align: center;
}

.count-number {
  font-size: 36rpx;
  font-weight: 700;
  color: var(--primary-color);
  display: block;
}

.count-label {
  font-size: 22rpx;
  color: var(--text-tertiary);
}

/* 成就进度 */
.achievement-list {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.achievement-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 25rpx;
  background: var(--background-light);
  border-radius: 16rpx;
}

.achievement-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: 3rpx solid #ddd;
}

.achievement-icon.unlocked {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  border-color: var(--primary-color);
}

.icon-text {
  font-size: 36rpx;
  filter: grayscale(100%);
}

.achievement-icon.unlocked .icon-text {
  filter: none;
}

.achievement-info {
  flex: 1;
}

.achievement-name {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 8rpx;
}

.achievement-desc {
  font-size: 24rpx;
  color: var(--text-tertiary);
  display: block;
  margin-bottom: 15rpx;
}

.achievement-progress {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.achievement-progress .progress-bar {
  flex: 1;
  height: 8rpx;
  background: var(--border-color);
  border-radius: 4rpx;
  overflow: hidden;
}

.achievement-progress .progress-fill {
  height: 100%;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
}

.achievement-progress .progress-text {
  font-size: 22rpx;
  color: var(--text-secondary);
  min-width: 80rpx;
  text-align: right;
}
</style>